

<!DOCTYPE html>
<html class="writer-html5" lang="en" >
<head>
  <meta charset="utf-8" />
  
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  
  <title>openspeech.criterion.ctc.ctc &mdash; Openspeech v0.3.0 documentation</title>
  

  
  <link rel="stylesheet" href="../../../../_static/css/theme.css" type="text/css" />
  <link rel="stylesheet" href="../../../../_static/pygments.css" type="text/css" />

  
  

  
  

  

  
  <!--[if lt IE 9]>
    <script src="../../../../_static/js/html5shiv.min.js"></script>
  <![endif]-->
  
    
      <script type="text/javascript" id="documentation_options" data-url_root="../../../../" src="../../../../_static/documentation_options.js"></script>
        <script src="../../../../_static/jquery.js"></script>
        <script src="../../../../_static/underscore.js"></script>
        <script src="../../../../_static/doctools.js"></script>
        <script src="../../../../_static/language_data.js"></script>
    
    <script type="text/javascript" src="../../../../_static/js/theme.js"></script>

    
    <link rel="index" title="Index" href="../../../../genindex.html" />
    <link rel="search" title="Search" href="../../../../search.html" /> 
</head>

<body class="wy-body-for-nav">

   
  <div class="wy-grid-for-nav">
    
    <nav data-toggle="wy-nav-shift" class="wy-nav-side">
      <div class="wy-side-scroll">
        <div class="wy-side-nav-search" >
          

          
            <a href="../../../../index.html" class="icon icon-home"> Openspeech
          

          
          </a>

          
            
            
          

          
<div role="search">
  <form id="rtd-search-form" class="wy-form" action="../../../../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>
</div>

          
        </div>

        
        <div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
          
            
            
              
            
            
              <p class="caption"><span class="caption-text">GETTING STARTED</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../../../notes/intro.html">Introduction</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../notes/hydra_configs.html">Openspeech’s Hydra configuration</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../notes/configs.html">Openspeech’s configurations</a></li>
</ul>
<p class="caption"><span class="caption-text">OPENSPEECH MODELS</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../../../models/Openspeech Model.html">Openspeech Model</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../models/Openspeech CTC Model.html">Openspeech CTC Model</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../models/Openspeech Encoder Decoder Model.html">Openspeech Encoder Decoder Model</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../models/Openspeech Transducer Model.html">Openspeech Transducer Model</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../models/Openspeech Language Model.html">Openspeech Language Model</a></li>
</ul>
<p class="caption"><span class="caption-text">MODEL ARCHITECTURES</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../../../architectures/Conformer.html">Conformer</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../architectures/ContextNet.html">ContextNet</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../architectures/DeepSpeech2.html">DeepSpeech2</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../architectures/Jasper.html">Jasper</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../architectures/Listen Attend Spell.html">Listen Attend Spell Model</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../architectures/LSTM LM.html">LSTM Language Model</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../architectures/QuartzNet.html">QuartzNet Model</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../architectures/RNN Transducer.html">RNN Transducer Model</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../architectures/Transformer.html">Transformer Model</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../architectures/Transformer LM.html">Transformer Language Model</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../architectures/Transformer Transducer.html">Transformer Transducer Model</a></li>
</ul>
<p class="caption"><span class="caption-text">CORPUS</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../../../corpus/AISHELL-1.html">AISHELL</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../corpus/KsponSpeech.html">KsponSpeech</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../corpus/LibriSpeech.html">LibriSpeech</a></li>
</ul>
<p class="caption"><span class="caption-text">LIBRARY REFERENCE</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../../../modules/Callback.html">Callback</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../modules/Criterion.html">Criterion</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../modules/Data Augment.html">Data Augment</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../modules/Feature Transform.html">Feature Transform</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../modules/Datasets.html">Datasets</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../modules/Data Loaders.html">Data Loaders</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../modules/Decoders.html">Decoders</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../modules/Encoders.html">Encoders</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../modules/Modules.html">Modules</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../modules/Optim.html">Optim</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../modules/Search.html">Search</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../modules/Tokenizers.html">Tokenizers</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../modules/Metric.html">Metric</a></li>
</ul>

            
          
        </div>
        
      </div>
    </nav>

    <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">

      
      <nav class="wy-nav-top" aria-label="top navigation">
        
          <i data-toggle="wy-nav-top" class="fa fa-bars"></i>
          <a href="../../../../index.html">Openspeech</a>
        
      </nav>


      <div class="wy-nav-content">
        
        <div class="rst-content">
        
          

















<div role="navigation" aria-label="breadcrumbs navigation">

  <ul class="wy-breadcrumbs">
    
      <li><a href="../../../../index.html" class="icon icon-home"></a> &raquo;</li>
        
          <li><a href="../../../index.html">Module code</a> &raquo;</li>
        
      <li>openspeech.criterion.ctc.ctc</li>
    
    
      <li class="wy-breadcrumbs-aside">
        
      </li>
    
  </ul>

  
  <hr/>
</div>
          <div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
           <div itemprop="articleBody">
            
  <h1>Source code for openspeech.criterion.ctc.ctc</h1><div class="highlight"><pre>
<span></span><span class="c1"># MIT License</span>
<span class="c1">#</span>
<span class="c1"># Copyright (c) 2021 Soohwan Kim and Sangchun Ha and Soyoung Cho</span>
<span class="c1">#</span>
<span class="c1"># Permission is hereby granted, free of charge, to any person obtaining a copy</span>
<span class="c1"># of this software and associated documentation files (the &quot;Software&quot;), to deal</span>
<span class="c1"># in the Software without restriction, including without limitation the rights</span>
<span class="c1"># to use, copy, modify, merge, publish, distribute, sublicense, and/or sell</span>
<span class="c1"># copies of the Software, and to permit persons to whom the Software is</span>
<span class="c1"># furnished to do so, subject to the following conditions:</span>
<span class="c1">#</span>
<span class="c1"># The above copyright notice and this permission notice shall be included in all</span>
<span class="c1"># copies or substantial portions of the Software.</span>
<span class="c1">#</span>
<span class="c1"># THE SOFTWARE IS PROVIDED &quot;AS IS&quot;, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR</span>
<span class="c1"># IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,</span>
<span class="c1"># FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE</span>
<span class="c1"># AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER</span>
<span class="c1"># LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,</span>
<span class="c1"># OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE</span>
<span class="c1"># SOFTWARE.</span>

<span class="kn">import</span> <span class="nn">torch.nn</span> <span class="k">as</span> <span class="nn">nn</span>
<span class="kn">from</span> <span class="nn">torch</span> <span class="kn">import</span> <span class="n">Tensor</span>
<span class="kn">from</span> <span class="nn">omegaconf</span> <span class="kn">import</span> <span class="n">DictConfig</span>

<span class="kn">from</span> <span class="nn">..</span> <span class="kn">import</span> <span class="n">register_criterion</span>
<span class="kn">from</span> <span class="nn">..ctc.configuration</span> <span class="kn">import</span> <span class="n">CTCLossConfigs</span>
<span class="kn">from</span> <span class="nn">...tokenizers.tokenizer</span> <span class="kn">import</span> <span class="n">Tokenizer</span>


<div class="viewcode-block" id="CTCLoss"><a class="viewcode-back" href="../../../../modules/Criterion.html#openspeech.criterion.ctc.ctc.CTCLoss">[docs]</a><span class="nd">@register_criterion</span><span class="p">(</span><span class="s2">&quot;ctc&quot;</span><span class="p">,</span> <span class="n">dataclass</span><span class="o">=</span><span class="n">CTCLossConfigs</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">CTCLoss</span><span class="p">(</span><span class="n">nn</span><span class="o">.</span><span class="n">Module</span><span class="p">):</span>
    <span class="sa">r</span><span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    The Connectionist Temporal Classification loss.</span>

<span class="sd">    Calculates loss between a continuous (unsegmented) time series and a target sequence. CTCLoss sums over the</span>
<span class="sd">    probability of possible alignments of input to target, producing a loss value which is differentiable</span>
<span class="sd">    with respect to each input node. The alignment of input to target is assumed to be &quot;many-to-one&quot;, which</span>
<span class="sd">    limits the length of the target sequence such that it must be :math:`\leq` the input length.</span>

<span class="sd">    Args:</span>
<span class="sd">        configs (DictConfig): hydra configuration set</span>
<span class="sd">        tokenizer (Tokenizer): tokenizer is in charge of preparing the inputs for a model.</span>

<span class="sd">    Inputs: log_probs, targets, input_lengths, target_lengths</span>
<span class="sd">        - Log_probs: Tensor of size :math:`(T, N, C)`,</span>
<span class="sd">          where :math:`T = \text{input length}`,</span>
<span class="sd">          :math:`N = \text{batch size}`, and</span>
<span class="sd">          :math:`C = \text{number of classes (including blank)}`.</span>
<span class="sd">          The logarithmized probabilities of the outputs (e.g. obtained with</span>
<span class="sd">          :func:`torch.nn.functional.log_softmax`).</span>
<span class="sd">        - Targets: Tensor of size :math:`(N, S)` or</span>
<span class="sd">          :math:`(\operatorname{sum}(\text{target\_lengths}))`,</span>
<span class="sd">          where :math:`N = \text{batch size}` and</span>
<span class="sd">          :math:`S = \text{max target length, if shape is } (N, S)`.</span>
<span class="sd">          It represent the target sequences. Each element in the target</span>
<span class="sd">          sequence is a class index. And the target index cannot be blank (default=0).</span>
<span class="sd">          In the :math:`(N, S)` form, targets are padded to the</span>
<span class="sd">          length of the longest sequence, and stacked.</span>
<span class="sd">          In the :math:`(\operatorname{sum}(\text{target\_lengths}))` form,</span>
<span class="sd">          the targets are assumed to be un-padded and</span>
<span class="sd">          concatenated within 1 dimension.</span>
<span class="sd">        - Input_lengths: Tuple or tensor of size :math:`(N)`,</span>
<span class="sd">          where :math:`N = \text{batch size}`. It represent the lengths of the</span>
<span class="sd">          inputs (must each be :math:`\leq T`). And the lengths are specified</span>
<span class="sd">          for each sequence to achieve masking under the assumption that sequences</span>
<span class="sd">          are padded to equal lengths.</span>
<span class="sd">        - Target_lengths: Tuple or tensor of size :math:`(N)`,</span>
<span class="sd">          where :math:`N = \text{batch size}`. It represent lengths of the targets.</span>
<span class="sd">          Lengths are specified for each sequence to achieve masking under the</span>
<span class="sd">          assumption that sequences are padded to equal lengths. If target shape is</span>
<span class="sd">          :math:`(N,S)`, target_lengths are effectively the stop index</span>
<span class="sd">          :math:`s_n` for each target sequence, such that ``target_n = targets[n,0:s_n]`` for</span>
<span class="sd">          each target in a batch. Lengths must each be :math:`\leq S`</span>
<span class="sd">          If the targets are given as a 1d tensor that is the concatenation of individual</span>
<span class="sd">          targets, the target_lengths must add up to the total length of the tensor.</span>

<span class="sd">    Returns: loss</span>
<span class="sd">        * loss (float): loss for training</span>

<span class="sd">    Examples::</span>

<span class="sd">        &gt;&gt;&gt; # Target are to be padded</span>
<span class="sd">        &gt;&gt;&gt; T = 50      # Input sequence length</span>
<span class="sd">        &gt;&gt;&gt; C = 20      # Number of classes (including blank)</span>
<span class="sd">        &gt;&gt;&gt; N = 16      # Batch size</span>
<span class="sd">        &gt;&gt;&gt; S = 30      # Target sequence length of longest target in batch (padding length)</span>
<span class="sd">        &gt;&gt;&gt; S_min = 10  # Minimum target length, for demonstration purposes</span>
<span class="sd">        &gt;&gt;&gt;</span>
<span class="sd">        &gt;&gt;&gt; # Initialize random batch of input vectors, for *size = (T,N,C)</span>
<span class="sd">        &gt;&gt;&gt; input = torch.randn(T, N, C).log_softmax(2).detach().requires_grad_()</span>
<span class="sd">        &gt;&gt;&gt;</span>
<span class="sd">        &gt;&gt;&gt; # Initialize random batch of targets (0 = blank, 1:C = classes)</span>
<span class="sd">        &gt;&gt;&gt; target = torch.randint(low=1, high=C, size=(N, S), dtype=torch.long)</span>
<span class="sd">        &gt;&gt;&gt;</span>
<span class="sd">        &gt;&gt;&gt; input_lengths = torch.full(size=(N,), fill_value=T, dtype=torch.long)</span>
<span class="sd">        &gt;&gt;&gt; target_lengths = torch.randint(low=S_min, high=S, size=(N,), dtype=torch.long)</span>
<span class="sd">        &gt;&gt;&gt; ctc_loss = nn.CTCLoss()</span>
<span class="sd">        &gt;&gt;&gt; loss = ctc_loss(input, target, input_lengths, target_lengths)</span>
<span class="sd">        &gt;&gt;&gt; loss.backward()</span>
<span class="sd">        &gt;&gt;&gt;</span>
<span class="sd">        &gt;&gt;&gt;</span>
<span class="sd">        &gt;&gt;&gt; # Target are to be un-padded</span>
<span class="sd">        &gt;&gt;&gt; T = 50      # Input sequence length</span>
<span class="sd">        &gt;&gt;&gt; C = 20      # Number of classes (including blank)</span>
<span class="sd">        &gt;&gt;&gt; N = 16      # Batch size</span>
<span class="sd">        &gt;&gt;&gt;</span>
<span class="sd">        &gt;&gt;&gt; # Initialize random batch of input vectors, for *size = (T,N,C)</span>
<span class="sd">        &gt;&gt;&gt; input = torch.randn(T, N, C).log_softmax(2).detach().requires_grad_()</span>
<span class="sd">        &gt;&gt;&gt; input_lengths = torch.full(size=(N,), fill_value=T, dtype=torch.long)</span>
<span class="sd">        &gt;&gt;&gt;</span>
<span class="sd">        &gt;&gt;&gt; # Initialize random batch of targets (0 = blank, 1:C = classes)</span>
<span class="sd">        &gt;&gt;&gt; target_lengths = torch.randint(low=1, high=T, size=(N,), dtype=torch.long)</span>
<span class="sd">        &gt;&gt;&gt; target = torch.randint(low=1, high=C, size=(sum(target_lengths),), dtype=torch.long)</span>
<span class="sd">        &gt;&gt;&gt; ctc_loss = CTCLoss()</span>
<span class="sd">        &gt;&gt;&gt; loss = ctc_loss(input, target, input_lengths, target_lengths)</span>
<span class="sd">        &gt;&gt;&gt; loss.backward()</span>

<span class="sd">    Reference:</span>
<span class="sd">        A. Graves et al.: Connectionist Temporal Classification:</span>
<span class="sd">        Labelling Unsegmented Sequence Data with Recurrent Neural Networks:</span>
<span class="sd">        https://www.cs.toronto.edu/~graves/icml_2006.pdf</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span>
            <span class="bp">self</span><span class="p">,</span>
            <span class="n">configs</span><span class="p">:</span> <span class="n">DictConfig</span><span class="p">,</span>
            <span class="n">tokenizer</span><span class="p">:</span> <span class="n">Tokenizer</span><span class="p">,</span>
    <span class="p">)</span> <span class="o">-&gt;</span> <span class="kc">None</span><span class="p">:</span>
        <span class="nb">super</span><span class="p">(</span><span class="n">CTCLoss</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="fm">__init__</span><span class="p">()</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">ctc_loss</span> <span class="o">=</span> <span class="n">nn</span><span class="o">.</span><span class="n">CTCLoss</span><span class="p">(</span>
            <span class="n">blank</span><span class="o">=</span><span class="n">tokenizer</span><span class="o">.</span><span class="n">blank_id</span><span class="p">,</span>
            <span class="n">reduction</span><span class="o">=</span><span class="n">configs</span><span class="o">.</span><span class="n">criterion</span><span class="o">.</span><span class="n">reduction</span><span class="p">,</span>
            <span class="n">zero_infinity</span><span class="o">=</span><span class="n">configs</span><span class="o">.</span><span class="n">criterion</span><span class="o">.</span><span class="n">zero_infinity</span><span class="p">,</span>
        <span class="p">)</span>

    <span class="k">def</span> <span class="nf">forward</span><span class="p">(</span>
            <span class="bp">self</span><span class="p">,</span>
            <span class="n">log_probs</span><span class="p">:</span> <span class="n">Tensor</span><span class="p">,</span>
            <span class="n">input_lengths</span><span class="p">:</span> <span class="n">Tensor</span><span class="p">,</span>
            <span class="n">targets</span><span class="p">:</span> <span class="n">Tensor</span><span class="p">,</span>
            <span class="n">target_lengths</span><span class="p">:</span> <span class="n">Tensor</span><span class="p">,</span>
    <span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">ctc_loss</span><span class="p">(</span>
            <span class="n">log_probs</span><span class="p">,</span>
            <span class="n">targets</span><span class="p">,</span>
            <span class="n">input_lengths</span><span class="p">,</span>
            <span class="n">target_lengths</span><span class="p">,</span>
        <span class="p">)</span></div>
</pre></div>

           </div>
           
          </div>
          <footer>

  <hr/>

  <div role="contentinfo">
    <p>
        &#169; Copyright 2021, Kim, Soohwan and Ha, Sangchun and Cho, Soyoung.

    </p>
  </div>
    
    
    
    Built with <a href="https://www.sphinx-doc.org/">Sphinx</a> using a
    
    <a href="https://github.com/readthedocs/sphinx_rtd_theme">theme</a>
    
    provided by <a href="https://readthedocs.org">Read the Docs</a>. 

</footer>
        </div>
      </div>

    </section>

  </div>
  

  <script type="text/javascript">
      jQuery(function () {
          SphinxRtdTheme.Navigation.enable(true);
      });
  </script>

  
  
    
   

</body>
</html>